package com.ly.oa.web.action;

import com.ly.oa.bean.Dept;
import com.ly.oa.utils.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet({"/dept/list", "/dept/add", "/dept/detail", "/dept/delete", "/dept/edit"})
public class DeptServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
////        获取session（这个session不需要新建）
////        只是获取当前session，获取不到返回null
//        HttpSession session = request.getSession(false);
//        if (session != null && session.getAttribute("username") != null) {
//            String servletPath = request.getServletPath();
//            if ("/dept/list".equals(servletPath)) {
//                doList(request, response);
//            } else if ("/dept/add".equals(servletPath)) {
//                doAdd(request, response);
//            } else if ("/dept/detail".equals(servletPath)) {
//                doDetail(request, response);
//            } else if ("/dept/delete".equals(servletPath)) {
//                doDel(request, response);
//            } else if ("/dept/edit".equals(servletPath)) {
//                doEdit(request, response);
//            }
//        }else {
////            跳转到登录页面
////            response.sendRedirect("/oa/index.jsp");
////            response.sendRedirect("/oa");
//            response.sendRedirect(request.getContextPath() + "/index.jsp"); // 访问web站点的根即可，自动找到欢迎页面
//        }

        String servletPath = request.getServletPath();
        if ("/dept/list".equals(servletPath)) {
            doList(request, response);
        } else if ("/dept/add".equals(servletPath)) {
            doAdd(request, response);
        } else if ("/dept/detail".equals(servletPath)) {
            doDetail(request, response);
        } else if ("/dept/delete".equals(servletPath)) {
            doDel(request, response);
        } else if ("/dept/edit".equals(servletPath)) {
            doEdit(request, response);
        }
    }

    /**
     * 修改部门信息
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void doEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        解决请求体的中文乱码问题
        request.setCharacterEncoding("UTF-8");
//        获取表单中的数据
        String deptno = request.getParameter("deptno");
        String dname = request.getParameter("dname");
        String loc = request.getParameter("loc");

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        int count = 0;

        try {
            conn = DBUtil.getConnection();
            String sql = "UPDATE dept SET dname = ?,loc = ? WHERE deptno = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, dname);
            ps.setString(2, loc);
            ps.setString(3, deptno);
            count = ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(conn, ps, rs);
        }

        if (count == 1) {
            response.sendRedirect(request.getContextPath() + "/dept/list");
        }
    }

    /**
     * 根据部门编号删除相关信息
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void doDel(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        获取部门编号
        String deptno = request.getParameter("deptno");

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        int count = 0;

        try {
            conn = DBUtil.getConnection();
//            开启事务（自动提交事务关闭）
            conn.setAutoCommit(false);
            String sql = "DELETE FROM dept WHERE deptno = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, deptno);
            count = ps.executeUpdate();
//            事务提交
            conn.commit();
        } catch (SQLException e) {
//            遇到异常需要回滚
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }
            }
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(conn, ps, rs);
        }

        if (count == 1) {
//            删除成功，重定向到列表页面
            response.sendRedirect(request.getContextPath() + "/dept/list");
        }
    }

    /**
     * 根据部门编号获取部门详细信息
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void doDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        创建部门对象
        Dept dept = new Dept();
//        获取部门编号
        String deptno = request.getParameter("dno");

//        根据部门编号获取部门信息，将部门信息封装成咖啡豆
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
//            获取连接
            conn = DBUtil.getConnection();
//            执行sql
            String sql = "SELECT dname,loc FROM dept WHERE deptno = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, deptno);
            rs = ps.executeQuery();

            if (rs.next()) {
                String dname = rs.getString("dname");
                String loc = rs.getString("loc");
//                封装对象
                dept.setDeptno(deptno);
                dept.setDname(dname);
                dept.setLoc(loc);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
//            释放资源
            DBUtil.close(conn, ps, rs);
        }

        request.setAttribute("dept", dept);

//        request.getRequestDispatcher("/detail.jsp").forward(request, response);

/*        String f = request.getParameter("f");
        if ("edit".equals(f)){
            request.getRequestDispatcher("/edit.jsp").forward(request, response);
        } else if ("detail".equals(f)) {
            request.getRequestDispatcher("/detail.jsp").forward(request, response);
        }*/

        String forward = "/" + request.getParameter("f") + ".jsp";
        request.getRequestDispatcher(forward).forward(request, response);
    }

    /**
     * 增加部门信息
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void doAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String deptno = request.getParameter("deptno");
        String dname = request.getParameter("dname");
        String loc = request.getParameter("loc");

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        int count = 0;

        try {
//            获取连接
            conn = DBUtil.getConnection();
//            执行sql
            String sql = "INSERT INTO dept VALUES (?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1, deptno);
            ps.setString(2, dname);
            ps.setString(3, loc);
            count = ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
//            释放资源
            DBUtil.close(conn, ps, rs);
        }

        if (count == 1) {
            response.sendRedirect(request.getContextPath() + "/dept/list");
        }

    }

    /**
     * 连接数据库，查询所有的部门信息，将部门信息收集好，然后跳转到JSP做页面展示
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void doList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        准备一个容器，用来专门存储部门
        List<Dept> depts = new ArrayList<>();

//        连接数据库，查询所有的部门信息
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
//            获取连接
            conn = DBUtil.getConnection();
//            执行查询语句
            String sql = "SELECT * FROM dept";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
//            遍历结果集
            while (rs.next()) {
                String deptno = rs.getString("deptno");
                String dname = rs.getString("dname");
                String loc = rs.getString("loc");

//                将以上零散的数据封装成java对象
                Dept dept = new Dept();
                dept.setDeptno(deptno);
                dept.setDname(dname);
                dept.setLoc(loc);

//                将部门对象放到list集合当中
                depts.add(dept);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
//            释放资源
            DBUtil.close(conn, ps, rs);
        }

//        将一个集合放到请求域当中
        request.setAttribute("deptList", depts);

//        转发（不要重定向）
        request.getRequestDispatcher("/list.jsp").forward(request, response);
    }
}
